package com.sp.scmdb.serviceImpl;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;
import com.sp.scmdb.bean.LeaderShipBean;
import com.sp.scmdb.common.CommonParamter;
import com.sp.scmdb.dao.EmployeeDao;
import com.sp.scmdb.dao.LeaderShipDao;
import com.sp.scmdb.dao.ShiftsDetailsDao;
import com.sp.scmdb.dao.ViewLeaderShipDao;
import com.sp.scmdb.entity.Employee;
import com.sp.scmdb.entity.LeaderShip;
import com.sp.scmdb.entity.ShiftsDetails;
import com.sp.scmdb.entity.ViewLeadership;
import com.sp.scmdb.service.LeadershipService;
import com.sp.scmdb.spring.ApplicationContext;
import com.sp.scmdb.webservice.model.LeadershipModel;
import com.sp.scmdb.webservice.model.ReturnResponse;
import com.sp.scmdb.webservice.service.UploadDataService;
import com.sp.scmdb.webservice.suport.CastorSerializer;

@Service("leadershipService")
public class LeadershipServiceImpl implements LeadershipService {

	private static Log log = LogFactory.getLog(LeadershipServiceImpl.class);
	private LeaderShipDao leaderShipDao;
	private ViewLeaderShipDao viewLeaderShipDao;
	private EmployeeDao employeeDao;
	private ShiftsDetailsDao shiftsDetailsDao;

	@Autowired
	public void setShiftsDetailsDao(ShiftsDetailsDao shiftsDetailsDao) {
		this.shiftsDetailsDao = shiftsDetailsDao;
	}

	@Autowired
	public void setEmployeeDao(EmployeeDao employeeDao) {
		this.employeeDao = employeeDao;
	}

	@Autowired
	public void setViewLeaderShipDao(ViewLeaderShipDao viewLeaderShipDao) {
		this.viewLeaderShipDao = viewLeaderShipDao;
	}

	@Autowired
	public void setLeaderShipDao(LeaderShipDao leaderShipDao) {
		this.leaderShipDao = leaderShipDao;
	}

	@Override
	public List<ViewLeadership> findAll(LeaderShipBean entity) {
		StringBuffer hql = new StringBuffer("from ViewLeadership where 1=1 ");
		if (StringUtils.isNotEmpty(entity.getWorkTime())) {
			hql.append("and workTime>='" + entity.getWorkTime() + "'");
		}
		List<ViewLeadership> leaderShips = viewLeaderShipDao.queryHql(hql
				.toString());
		return leaderShips;
	}

	@SuppressWarnings("finally")
	public String uplaodLeadership(String uploadID) {
		String result = CommonParamter.CHECK_FAIL;
		try {
			List<ViewLeadership> leaderShips = viewLeaderShipDao
					.queryHql("from ViewLeadership");
			if (CollectionUtils.isNotEmpty(leaderShips)) {
				CastorSerializer serializerTool = new CastorSerializer();
				ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
				LeadershipModel leadershipModel = new LeadershipModel();
				leadershipModel.setUserId(CommonParamter.userID);
				leadershipModel.setPassword(CommonParamter.password);
				leadershipModel.setListLeader(leaderShips);
				serializerTool
						.addMappingLocation("com/sp/scmdb/webservice/mapping/mapping.xml");
				serializerTool.marshal(leadershipModel, byteOutputStream,
						"UTF-8");
				String str = new String(byteOutputStream.toByteArray());
				UploadDataService upload = (UploadDataService) ApplicationContext
						.getBean("uploadService");
				result = upload.uploadLeadership(str);
				System.out.println(str);
				ReturnResponse response = (ReturnResponse) serializerTool
						.unmarshal(new ByteArrayInputStream(result.getBytes()),
								"GB2312");
				result = response.getDescription();
			}
		} catch (javax.xml.ws.WebServiceException e) {
			if ("Could not send Message.".equals(e.getMessage())) {
				result = "timeOut";
			}
			result=e.getMessage();
		} catch (Exception e) {
			log.error(e.getMessage());
		} finally {
			return result;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Employee> leaderEmps() {
		List<Employee> empLists = Lists.newArrayList();
		String hql = "from Employee emp, Duty duty,DutyLevel dLevel where emp.empDutyID = duty.id and duty.dutyLevelId=dLevel.id and dLevel.levelID<=3 ";
		List empList = employeeDao.findByHql(hql);
		if (CollectionUtils.isNotEmpty(empList)) {
			Iterator iterator1 = empList.iterator();
			while (iterator1.hasNext()) {
				Object[] object = (Object[]) iterator1.next();
				Employee emp = (Employee) object[0];
				empLists.add(emp);
			}
		}
		return empLists;
	}

	public List<ShiftsDetails> shiftList() {
		List<ShiftsDetails> shifts = Lists.newArrayList();
		shifts = shiftsDetailsDao.queryAll();
		return shifts;
	}

	@Transactional
	public String addLeadership(LeaderShipBean entity) {
		String result = CommonParamter.CHECK_SUCCESS;
		try {
			LeaderShip leadership = new LeaderShip();
			leadership.setEmpID(entity.getLeaderName());
			leadership.setWorkTime(new LocalDate(entity.getWorkTime()));
			leadership.setShiftsDetailID(entity.getShiftDetailName());
			leaderShipDao.save(leadership);
			return result;
		} catch (Exception e) {
			throw new IllegalStateException(e.getMessage());
		}

	}

	@Transactional
	public String updateLeadership(LeaderShipBean entity) {
		String result = CommonParamter.CHECK_SUCCESS;
		try {
			LeaderShip leadership = new LeaderShip();
			leadership.setId(entity.getLeadershiftID());
			leadership.setEmpID(entity.getLeaderName());
			leadership.setWorkTime(new LocalDate(entity.getWorkTime()));
			leadership.setShiftsDetailID(entity.getShiftDetailName());
			leaderShipDao.update(leadership);
			return result;
		} catch (Exception e) {
			throw new IllegalStateException(e.getMessage());
		}
	}

	@Transactional
	public String delLeadership(String delID) {
		String result = CommonParamter.CHECK_SUCCESS;
		try {
			LeaderShip leadership = new LeaderShip();
			String[] delIDArr = delID.split(",");
			for (int i = 0; i < delIDArr.length; i++) {
				leadership = leaderShipDao.getById(Integer
						.parseInt(delIDArr[i]));
				if (leadership != null) {
					leaderShipDao.delete(leadership);
				}
			}
			result = CommonParamter.CHECK_SUCCESS;
			return result;
		} catch (Exception e) {
			throw new IllegalStateException(e.getMessage());
		}
	}

	@Transactional
	public LeaderShip findLeaderBean(String leadershipID) {
		LeaderShip leadership = leaderShipDao.getById(Integer
				.parseInt(leadershipID));
		return leadership;
	}

}
